package com.jamal2362.apktool.task;

import android.content.Context;
import brut.androlib.Androlib;
import brut.androlib.ApkOptions;
import brut.androlib.meta.MetaInfo;
import brut.util.OS;
import java.io.File;
import java.util.logging.Level;
import com.jamal2362.apktool.R;
import com.jamal2362.apktool.fragment.files.Refreshable;
import com.jamal2362.apktool.util.FileUtils;
import com.jamal2362.apktool.util.Settings;
import com.jamal2362.apktool.util.aapt2.fixAll;

public class BuildTask extends AbstractTask
{
	private final SignUtil signTool;
	private Context mContext;
	private boolean antiSplit;
	private File tempDir;
	private Refreshable refresh;

	public BuildTask(Context ctx, Refreshable refresh, SignUtil signTool)
	{
		super(ctx, refresh);
		this.signTool = signTool;
		this.mContext = ctx;
		this.refresh = refresh;
		this.antiSplit = false;
	}

	@Override
	protected int getTitle()
	{
		return R.string.build_run_title;
	}

	public void antiSplit(boolean b)
	{
		this.antiSplit = b;
	}

	@Override
	protected boolean process(File f)
	{
		if (Settings.useAapt2)
		{
			if (Settings.getb(mContext, "fix1056", true))
			{
				info(R.string.fix1056_aapt2, (Object) null);
				fixAll.replace1056to80(f);
			}
			fixAll.fixIds(f);
		}
		ApkOptions options = ApkOptions.INSTANCE;
		if (antiSplit)
			options.copyOriginalFiles = false;
		Androlib alib = new Androlib(options, this);
		try
		{
			File tmp = File.createTempFile("APKTOOL_M", null);
			try
			{
				MetaInfo meta = alib.build(f, tmp);
				File outDir = f;
				String outApk = FileUtils.genNameApk(mContext, outDir.getAbsolutePath(), meta.apkFileName, "_src", 0);
				if (antiSplit)
				{
					outDir = f.getParentFile().getParentFile();
					outApk = FileUtils.genNameApk(mContext, outDir.getAbsolutePath(), meta.apkFileName, "_antisplit", 0);
					tempDir = f.getParentFile();
				}
				File out = new File(outDir, outApk);
				int min;
				if (meta.sdkInfo != null)
					min = Integer.parseInt(meta.sdkInfo.get("minSdkVersion"));
				else
					min = 14;
				signTool.sign(tmp, out, min, this);
				setResult(out);
			}
			finally
			{
				tmp.delete();
			}
			return true;
		}
		catch (Exception e)
		{
			log(Level.WARNING, e.getMessage(), e);
			return false;
		}
	}

	@Override
	protected Boolean doInBackground(File[] p1)
	{
		boolean result = super.doInBackground(p1);
		if (antiSplit && result)
		{
			info(R.string.deletion, tempDir.getAbsolutePath());
			OS.rmdir(tempDir);
		}
		return result;
	}
}
